/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package core;

import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import datamodel.Message;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import network.Connection;
import view.BasicForm;
import view.ConfirmConnectToExtraIPMessage;
import view.MessageBox;
import view.MessageForm;

/**
 *
 * @author Kvest
 */
public class ScreenEngine 
{
    private static ScreenEngine engine;
    private static final Object lockObject = new Object();

    private final Vector queue;
    
    private MessageBox messageBox;
    private MessageForm messageForm; 
    private static int IDs = 0;
    
    public static ScreenEngine getEngine()
    {
        synchronized(lockObject)
        {
            if (engine == null)
            {
                engine = new ScreenEngine();
            }
        }

        return engine;
    }

    private ScreenEngine()
    {
        queue = new Vector();
    }
   
    public boolean containsForm(Form form) {
        synchronized(queue){
            return queue.contains(form);
        }
    }
    
    public void push(Form form)
    {
        synchronized(queue)
        {
            if (queue.size() > 0 && (queue.elementAt(queue.size() - 1) instanceof BasicForm))
            {
                ((BasicForm)queue.elementAt(queue.size() - 1)).hide();
            }
            queue.addElement(form);
        }

        form.show();
    }
    
    public void popTo(int index)
    {
        synchronized(queue)
        {
            for (int i = queue.size() - 1; i > index; --i)
            {
                if (queue.size() > 0 && (queue.elementAt(i) instanceof BasicForm))
                {
                    ((BasicForm)queue.elementAt(i)).hide();
                }
                queue.removeElementAt(i);
            }
            
            if (queue.size() > 0)
            {
                ((Form)queue.elementAt(queue.size() - 1)).show();
                
                //Костыль, иначе не предыдущая форма
                try
                {
                    Thread.sleep(50);
                }catch(Exception ex){}
            }
        }
    }
    
     public Form pop(boolean showPreviouse)
    {
        synchronized(queue)
        {
            if (queue.size() == 0)
            {
                return null;
            }
            else
            {
                Form result = (Form)queue.elementAt(queue.size() - 1);// lastElement();
                if (result instanceof BasicForm)
                {
                    ((BasicForm)result).hide();
                }
                queue.removeElement(result);
                if (showPreviouse)
                {
                    ((Form)queue.elementAt(queue.size() - 1)).show();

                    //Костыль, иначе не предыдущая форма
                    try
                    {
                        Thread.sleep(50);
                    }catch(Exception ex){}
                }

                return result;
            }
        }
    }
     
    public void showCurrent()
    {
        synchronized(queue)
        {   
            if (queue.size() > 0)
            {
                ((Form)queue.elementAt(queue.size() - 1)).show();

                //Костыль, иначе не отобразит эту форму
                try
                {
                    Thread.sleep(50);
                }catch(Exception ex){}
            }
        }
    }
    
    public Form getBeforeCurrent()
    {
        synchronized(queue)
        {
            if (queue.size() < 2)
            {
                return null;
            }
            else
            {
                return (Form)queue.elementAt(queue.size() - 2);
            }
        }
    }
    
    public Form getForm(int index)
    {
        synchronized(queue)
        {
            if (queue.size() == 0 || index >= queue.size())
            {
                return null;
            }
            else
            {
                return (Form)queue.elementAt(index);
            }
        }
    }
    
    public Form getCurrent()
    {
        synchronized(queue)
        {
            if (queue.size() == 0)
            {
                return null;
            }
            else
            {
                return (Form)queue.elementAt(queue.size() - 1);
            }
        }
    }
    
    public int getScreensCount()
    {
        synchronized(queue)
        {
            return queue.size();
        }
    }
    
    public void showMessage(String title, Message message, long timeout)
    {
        if (messageForm == null)
        {
            messageForm = new MessageForm();
        }
        
        //Утанавливаем данные
        messageForm.setTitle(title);
        messageForm.setMessage(message);
        
        
        final int messageFormId = ++IDs;        
        messageForm.setTag(messageFormId);
        
        //Отображаем
        push(messageForm);
        
        //Если надо - запускаем таймер
        if (timeout > 0)
        {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() 
            {
                public void run()
                {
                    synchronized(queue)
                    {
                        if (getCurrent() == messageForm && messageForm.getTag() == messageFormId)
                        {                      
                            pop(true);
                        }
                    }
                }
            }, timeout);
        }
    }
   
    public void confirmConnectToExtraIP() {
        //создаем
        ConfirmConnectToExtraIPMessage message = new ConfirmConnectToExtraIPMessage(new ConfirmConnectToExtraIPMessage.OnConfirmListener() {
            public void onConfirm() {
                if (Settings.getSettings().getExtraServerIP().equals("")) {
                    ScreenEngine.getEngine().showMessageBox("error", (new Label("no_extra_ip")).getText(), -1);
                } else {
                    Connection.getConnection().startReconnectTimer();
                }
            }
        });
        
        //Отображаем
        push(message);
    }
    
    public void showMessageBox(String title, String message, long timeout)
    {
        if (messageBox == null)
        {
            messageBox = new MessageBox();
        }
        //Утанавливаем данные
        messageBox.setText(title, message);
        
        final int messageBoxId = ++IDs;        
        messageBox.setTag(messageBoxId);
        
        //Отображаем
        push(messageBox);
        
        //Если надо - запускаем таймер
        if (timeout > 0)
        {
            Timer timer = new Timer();
                   
            timer.schedule(new TimerTask() 
            {
                public void run()
                {               
                    synchronized(queue)
                    {
                        if (getCurrent() == messageBox && messageBox.getTag() == messageBoxId)
                        {                             
                            pop(true);
                        }
                    }
                }
            }, timeout);
        }
    }
}
